package org.test.springbootdisplaypage.tools;

import java.security.SecureRandom;

public class RandomString {
    private static final String LETTERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private static final String CHARACTERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_";
    private static final SecureRandom random = new SecureRandom();

    // 这个方法专门用来生成个人的用户名的---用户名是唯一的
    public static String generateRandomString(int length) {
        StringBuilder sb = new StringBuilder(length);
        // 首先添加一个随机字母
        int randomIndex = random.nextInt(LETTERS.length());
        char randomChar = LETTERS.charAt(randomIndex);
        sb.append(randomChar);

        // 然后添加其余的随机字符
        for (int i = 1; i < length; i++) {
            randomIndex = random.nextInt(CHARACTERS.length());
            randomChar = CHARACTERS.charAt(randomIndex);
            sb.append(randomChar);
        }
        return sb.toString();
    }
}